<template>
    <div v-loading="pageLoading">
        <el-button
            type="primary"
            class="mb8"
            :disabled="tableData.length === auditTypeList.length"
            @click="drawer = true"
            >审批流设置</el-button
        >
        <!-- 搜索 -->
        <BasicTable
            :columns="columns"
            :height="120"
            :table-data="tableData"
            :row-config="rowConfig"
            :table-loading="tableLoading"
            :page-info="pageInfo"
            :empty-info="{ text: '暂无审批流信息，请先进行审批流设置' }"
            @onChangePage="(pageInfo: any) => searchList(FormData, pageInfo)"
        >
            <template #index="scope">{{ scope.$index + 1 }}</template>
            <template #auditType="scope">{{ auditTypeMap[scope.row.auditType] }}</template>
            <template #updateTime="scope">{{ formatDate2(scope.row.updateTime, 'YYYY-MM-DD HH:mm:ss') }}</template>
            <template #currentAuditUsers="scope">{{
                scope.row.currentAuditUsers ? scope.row.currentAuditUsers : '-'
            }}</template>
        </BasicTable>

        <!-- 抽屉 -->
        <el-drawer
            v-if="drawer"
            v-model="drawer"
            title="审批流设置"
            direction="rtl"
            custom-class="customer-drawer"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            @close="handleCloseDrawer"
        >
            <div class="drawer-content">
                <el-select v-model="formData.auditType" clearable placeholder="请选择" class="select">
                    <template #prefix>
                        <div class="label">选择表单</div>
                    </template>
                    <el-option
                        v-for="(item, index) in auditTypeList"
                        :key="index"
                        :label="item.label"
                        :value="item.val"
                        :disabled="tableData.map((v: any) => v.auditType).includes(item.val)"
                    />
                </el-select>
                <div class="flex-box info">
                    <div class="l">
                        <div class="t">
                            当前选择人数（{{ formData.auditConfReqs.length }}/{{ +formData.auditType === 4 ? 1 : 5 }}）
                        </div>
                        <div class="box">
                            <el-select
                                v-model="formData.auditConfReqs"
                                filterable
                                :disabled="formData.auditConfReqs.length === (+formData.auditType === 4 ? 1 : 5)"
                                multiple
                                collapse-tags
                                value-key="userId"
                                placeholder="请输入同事名称或选择同事"
                                @change="onChange"
                            >
                                <el-option
                                    v-for="item in userList"
                                    :key="item.userId"
                                    :label="item.userName"
                                    :value="item"
                                >{{ item.userName }} ({{ item.userNo }})</el-option
                                >
                            </el-select>
                            <div class="tags">
                                <draggable
                                    v-model="formData.auditConfReqs"
                                    item-key="userId"
                                    animation="300"
                                    @start="drag = true"
                                    @end="drag = false"
                                >
                                    <template #item="{ element }">
                                        <XcTag
                                            closable
                                            :text="`${formData.auditConfReqs.findIndex((item: any) => item.userId === element.userId) + 1} ${
                                                element.userName
                                            } (${element.userNo})`"
                                            size="large"
                                            @close="
                                                formData.auditConfReqs.splice(
                                                    formData.auditConfReqs.findIndex(
                                                        (item: any) => item.userId === element.userId
                                                    ),
                                                    1
                                                )
                                            "
                                        />
                                    </template>
                                </draggable>
                            </div>
                        </div>
                    </div>
                    <div class="r">
                        <div class="t">审批顺序（从下往上逐级审批）</div>
                        <div class="box">
                            <div v-if="formData.auditConfReqs.length" style="height: 100%">
                                <el-steps direction="vertical">
                                    <el-step
                                        v-for="(step, index) in reverseArr"
                                        :key="step"
                                        :title="`${step.userName} (${step.userNo})`"
                                    >
                                        <template #icon>{{ formData.auditConfReqs.length - index }}</template>
                                        <template #description>{{
                                            filterText(formData.auditConfReqs.length - index)
                                        }}</template>
                                    </el-step>
                                </el-steps>
                            </div>
                            <div v-else class="empty">暂无审批信息</div>
                        </div>
                    </div>
                </div>
            </div>
            <template #footer>
                <div>
                    <el-button size="large" @click="handleCloseDrawer">取消</el-button>
                    <el-button size="large" type="primary" :loading="drawerloading" @click="handleSubmit"
                        >发布</el-button
                    >
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue';

import BasicTable from '@/components/BasicTable.vue';
import XcTag from '@x-tech/fe-pc-components/src/components/XcTag/index.vue';
import draggable from 'vuedraggable';
import { TableData, FormData } from './ModelDefines';
import { getList, updataAndEdit } from '@/api/auditManage';
import { getUserList } from '@/api/delivery/customerManage';
import { formatDate2 } from '@x-tech/fe-utils/dist/date';
import { ElMessage } from 'element-plus';

import { useStore } from 'vuex';

// 加盟商编码（登录时已保存）
const store = useStore();

const userList: any = ref([]);

const groupCodeRef = computed(() => store.state.userGroup.groupCode || '');

const pageLoading = ref(false);

const drawer = ref(false);
const drawerloading = ref(false);
const drag = ref(false);

const formData = ref({
    auditType: '',
    auditConfReqs: [],
});

// eslint-disable-next-line vue/no-side-effects-in-computed-properties
const reverseArr = computed(() => JSON.parse(JSON.stringify(formData.value.auditConfReqs)).reverse());

const auditTypeList = ref([
    { label: '报价审批', val: 1 },
    { label: '签约审批', val: 2 },
    { label: '归档审批', val: 3 },
    { label: '特价申请', val: 4 },
    { label: '变更申请', val: 5 },
]);

const auditTypeMap = {
    1: '报价审批',
    2: '签约审批',
    3: '归档审批',
    4: '特价申请',
    5: '变更申请',
};

const tableLoading = ref(false);
const tableData = ref<TableData[]>([]);
const pageInfo = reactive({
    pageNum: 1,
    total: 0,
    pageSize: 10,
});

const columns = [
    { label: '序号', key: 'index', render: true },
    { label: '表单名称', key: 'auditType', render: true },
    { label: '最后更新时间', key: 'updateTime', render: true },
    { label: '最后更新人 ', key: 'updateUserName' },
    { label: '当前审批人', key: 'currentAuditUsers', render: true },
];

const isEdit = ref(false);

const rowConfig = [
    {
        color: '#4D88FF',
        name: '编辑',
        on: async ({ row }: { row: any }) => {
            formData.value.auditType = row.auditType;
            formData.value.auditConfReqs = row.users.map((item: any) => {
                return {
                    userName: item.name,
                    userNo: item.userNo,
                    userId: item.userId,
                };
            });
            // userList.value = JSON.parse(JSON.stringify(formData.value.auditConfReqs));
            isEdit.value = true;
            drawer.value = true;
        },
    },
];

const filterText = (index: number): string => {
    const textArr = ['初级审核员', '二级审核员', '三级审核员', '四级审核员', '终极审核员'];
    const len = formData.value.auditConfReqs.length;
    if (index === 1) {
        return textArr[0];
    }
    if (len > 1 && index === len) {
        return textArr[4];
    }
    return textArr[index - 1];
};

const searchList = async (formData: any, pageObj: any) => {
    // 表单重置的时候 分页设置为1
    pageInfo.pageNum = pageObj?.pageNum ? pageObj?.pageNum : pageInfo.pageNum;
    pageInfo.pageSize = pageObj?.pageSize ? pageObj?.pageSize : pageInfo.pageSize;
    const params = Object.assign(formData, {
        pageNum: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
    });
    tableLoading.value = true;
    try {
        const data = await getList(params);
        tableData.value = data.list ? data.list : [];
        pageInfo.total = data.list ? data.total : 0;
    } finally {
        tableLoading.value = false;
    }
};

const handleCloseDrawer = () => {
    drawer.value = false;
    drawerloading.value = false;
    formData.value.auditType = '';
    formData.value.auditConfReqs = [];
};

const handleSubmit = async () => {
    drawerloading.value = true;
    if (!formData.value.auditType) {
        ElMessage.warning('请选择表单');
        return;
    }
    if (!formData.value.auditConfReqs.length) {
        ElMessage.warning('请选择审批人');
        return;
    }
    try {
        const params = formData.value.auditConfReqs.map((item: any) => {
            return {
                auditType: formData.value.auditType,
                auditUserCode: item.userNo,
            };
        });
        await updataAndEdit(params);
        ElMessage.success('操作成功');
        pageInfo.pageNum = 1;
        searchList(FormData, {});
    } finally {
        handleCloseDrawer();
    }
};

const onChange = (val: any) => {
    console.log(val);
    if (+formData.value.auditType === 4) {
        if (val.length > 1) {
            formData.value.auditConfReqs.pop();
        }
    }
    if (val.length > 5) {
        formData.value.auditConfReqs.pop();
    }
};

onMounted(async () => {
    searchList(FormData, {});
    const data = await getUserList({ departCode: groupCodeRef.value, name: '' });
    userList.value = data.list ? data.list : [];
});
</script>

<style lang="scss" scoped>
.flex-box {
    display: flex;
}
.flex {
    flex: 1;
}
.mb8 {
    margin-bottom: 8px;
}
.align-center {
    align-items: center;
}
.drawer-content {
    .select {
        width: 280px;
        margin-bottom: 20px;
    }
    .info {
        .t {
            font-family: PingFangSC-Regular;
            font-weight: 400;
            font-size: 14px;
            color: #999;
            margin-bottom: 10px;
        }
        .l {
            margin-right: 20px;
            flex-basis: 300px;
            .tags {
                margin-top: 20px;
                .el-tag {
                    margin-right: 10px;
                    margin-bottom: 10px;
                    &:hover {
                        cursor: move;
                    }
                }
            }
        }
        .r {
            flex-basis: 216px;
            .box {
                display: flex;
                align-items: center;
                justify-content: center;
            }
        }
        .box {
            height: 400px;
            border: 1px solid #ededed;
            padding: 20px;
            box-sizing: border-box;
            .empty {
                @extend .t;
                margin-bottom: 0;
            }
        }
    }
}
::v-deep(.customer-drawer) {
    width: 584px !important;
    .el-drawer__header {
        .el-drawer__title {
            color: #333;
            font-size: 24px;
            font-weight: 700;
            font-family: 'PingFang SC';
        }
    }
}
::v-deep(.el-step__icon, .el-step__head.is-process .el-step__icon) {
    background-color: transparent !important;
    color: #e60044 !important;
    border: 1px solid #e60044 !important;
}
::v-deep(.el-step.is-vertical .el-step__main) {
    min-width: 100px;
    padding-left: 12px;
}
::v-deep(.el-step.is-vertical .el-step__title) {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 14px;
    color: #252525;
}
::v-deep(.el-step__description) {
    font-family: PingFangSC-Regular;
    font-weight: 400;
    font-size: 14px;
    color: #999;
}
::v-deep(.el-step) {
    flex: 1;
    flex-basis: inherit !important;
    &:last-of-type.is-flex {
        flex: 1;
        flex-basis: inherit !important;
    }
}
</style>
